﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using VSWClient.Tcp;
using VSWClient.Utility;
using System.Data;
using VSWClient.Tables;
using System.Diagnostics;
using VSWClient.Pages.Tables.L2PDB;

namespace VSWClient.Pages
{
    /// <summary>
    /// Page_User.xaml interaction logic
    /// </summary>
    public partial class Page_User : Page
    {
		public string btn_SaveUser_Content = "";
		TcpClient client;
		int queryUser_Index = 1;//user table data current page
		int queryUser_Pagenum = 20;//numbers of user table data per page
		bool is_change_pagenum = true;//whether to change the number of pages
		string user_sql = "";

		public Page_User(TcpClient tcp)
        {
            InitializeComponent();
			client = tcp;
			client.DealMessageHandler += Client_DealMessageHandler;
		}

		private void Page_Loaded(object sender, RoutedEventArgs e)
		{			
			Grid_UserDetail.IsEnabled = true;
			textBox_UserID.IsEnabled = true;
			client.SendMessage(Identity.definedCommand, Identity.selectUSER_BYINDEX, ((queryUser_Index - 1) * queryUser_Pagenum).ToString() + ";" + (queryUser_Index * queryUser_Pagenum).ToString());
			textBox_UserManagePage.Text = queryUser_Index.ToString();
			if (SHIFT_TABLE.shifttable != null)
			{
				RefreshUserManagerList(SHIFT_TABLE.shifttable);
			}
			if (TEAM_TABLE.teamtable != null)
			{
				RefreshUserManagerList(TEAM_TABLE.teamtable);
			}
		}

		#region User/Shift Refresh
		/// <summary>
		/// user table data refresh button
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btn_UpdateUsers_Click(object sender, RoutedEventArgs e)
		{
			string userid = textBox_UserID.Text.ToString();
			if (userid != "")
			{
				client.SendMessage(Identity.definedCommand, Identity.select_USERINFO, userid);
			}
			else
			{
				client.SendMessage(Identity.definedCommand, Identity.selectUSER_BYINDEX, ((queryUser_Index - 1) * queryUser_Pagenum).ToString() + ";" + (queryUser_Index * queryUser_Pagenum).ToString());
			}
			Grid_UserDetail.IsEnabled = false;
			btn_SaveUser_Content = "";
			textBox_UserID.IsEnabled = false;
			textBox_UserName.IsEnabled = false;
			textBox_UserPassword.IsEnabled = false;
			textBox_UserConfirmPassword.IsEnabled = false;
			comboBox_UserDepartment.IsEnabled = false;
			comboBox_UserLevel.IsEnabled = false;
			comboBox_UserShift.IsEnabled = false;
		}
		/// <summary>
		/// shift table data refresh button
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btn_ShiftUpdate_Click(object sender, RoutedEventArgs e)
		{
			client.SendMessage(Identity.definedCommand, Identity.refrushShiftTable, "");
		}
		#endregion

		#region User page up/down
		/// <summary>
		/// user table data page up
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btn_UpPage_UserManage_Click(object sender, RoutedEventArgs e)
		{
			if (queryUser_Index > 1)
			{
				queryUser_Index--;
				textBox_UserManagePage.Text = queryUser_Index.ToString();
				client.SendMessage(Identity.definedCommand, Identity.selectUSER_BYINDEX, ((queryUser_Index - 1) * queryUser_Pagenum).ToString() + ";" + (queryUser_Index * queryUser_Pagenum).ToString());
			}
		}
		/// <summary>
		/// user table data page down
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btn_DownPage_UserManage_Click(object sender, RoutedEventArgs e)
		{
			if (is_change_pagenum && Convert.ToInt32(textBox_UserManagePage.Text) < Convert.ToInt32(textBox_UserManageTotalPages.Text))
			{
				queryUser_Index++;
				textBox_UserManagePage.Text = queryUser_Index.ToString();
				client.SendMessage(Identity.definedCommand, Identity.selectUSER_BYINDEX, ((queryUser_Index - 1) * queryUser_Pagenum).ToString() + ";" + (queryUser_Index * queryUser_Pagenum).ToString());
			}
		}
		#endregion

		#region Client Receive Message
		private void Client_DealMessageHandler(object sender, DealMessageHandlerArgs e)
		{
			try
			{
				for (int i = 0; i < e.Message.Length; i++)
				{
					TcpMessageHelper msg = new TcpMessageHelper(e.Message[i]);
					//determine whether the command is valid
					if (msg.Vaild)
					{
						switch (msg.CommandId)
						{
							case Identity.select_USERINFO:
								{
									if (msg.Status)
									{
										DataTable usertable = JsonHelper.DeserializeJsonToObject<DataTable>(msg.Parameter[0]);
										if (usertable.Rows.Count < queryUser_Pagenum)
										{
											is_change_pagenum = false;
										}
										else
										{
											is_change_pagenum = true;
										}
										Dispatcher.Invoke(new Action(() =>
										{
											usertable.TableName = USER_TABLE.tableName;
											RefreshUserManagerList(usertable);
										}
										));
									}
									else
									{
										is_change_pagenum = false;
										if (queryUser_Index > 1)
										{
											queryUser_Index--;
										}
										//Dispatcher.Invoke(new Action(() =>
										//{
										//	dataGrid_UserDetail.ItemsSource = null;
										//}
										//));										
										MessageBox.Show(msg.Parameter[0]);
									}
									break;
								}
							case Identity.selectUSER_BYINDEX:
								{
									if (msg.Status)
									{
										DataTable usertable = JsonHelper.DeserializeJsonToObject<DataTable>(msg.Parameter[0]);
										string totalPages = msg.Parameter[1];
										if (usertable.Rows.Count < queryUser_Pagenum)
										{
											if (usertable.Rows.Count == 0)
											{
												queryUser_Index--;
											}
											is_change_pagenum = false;
										}
										else
										{
											is_change_pagenum = true;
										}
										Dispatcher.Invoke(new Action(() =>
										{
											usertable.TableName = USER_TABLE.tableName;
											RefreshUserManagerList(usertable);
											textBox_UserManageTotalPages.Text = totalPages;
										}
										));
									}
									else
									{
										is_change_pagenum = false;
										if (queryUser_Index > 1)
										{
											queryUser_Index--;
										}
										MessageBox.Show(msg.Parameter[0]);
									}
									break;
								}
							case Identity.insert_USER:
								{
									if (msg.Status)
									{
										Dispatcher.Invoke(new Action(() =>
										{
											DataTable usertable = JsonHelper.DeserializeJsonToObject<DataTable>(msg.Parameter[0]);
											string totalPages = msg.Parameter[1];
											usertable.TableName = USER_TABLE.tableName;
											RefreshUserManagerList(usertable);
											Dispatcher.Invoke(new Action(() =>
											{
												textBox_UserID.Text = "";
												textBox_UserName.Text = "";
												textBox_UserPassword.Password = "";
												textBox_UserConfirmPassword.Password = "";
												comboBox_UserDepartment.Text = "";
												comboBox_UserLevel.Text = "";
												comboBox_UserShift.Text = "";
												textBox_UserManageTotalPages.Text = totalPages;
											}
											));
										}
										));
									}
									else
									{
										MessageBox.Show("insert User failed");
									}
									break;
								}
							case Identity.update_USER:
								{
									if (msg.Status)
									{
										Dispatcher.Invoke(new Action(() =>
										{
											DataTable usertable = JsonHelper.DeserializeJsonToObject<DataTable>(msg.Parameter[0]);
											usertable.TableName = USER_TABLE.tableName;
											RefreshUserManagerList(usertable);

											textBox_UserID.Text = "";
											textBox_UserName.Text = "";
											textBox_UserPassword.Password = "";
											textBox_UserConfirmPassword.Password = "";
											comboBox_UserDepartment.Text = "";
											comboBox_UserLevel.Text = "";
											comboBox_UserShift.Text = "";
										}
										));
									}
									else
									{
										MessageBox.Show("User modify failed");
									}
									break;
								}
							case Identity.delete_USER:
								{
									if (msg.Status)
									{
										DataTable usertable = JsonHelper.DeserializeJsonToObject<DataTable>(msg.Parameter[0]);
										string totalPages = msg.Parameter[1];
										usertable.TableName = USER_TABLE.tableName;
										RefreshUserManagerList(usertable);
										Dispatcher.Invoke(new Action(() =>
										{
											textBox_UserID.Text = "";
											textBox_UserName.Text = "";
											textBox_UserPassword.Password = "";
											textBox_UserConfirmPassword.Password = "";
											comboBox_UserDepartment.Text = "";
											comboBox_UserLevel.Text = "";
											comboBox_UserShift.Text = "";
											textBox_UserManageTotalPages.Text = totalPages;
										}
										));
									}
									else
									{
										MessageBox.Show("User delete failed");
									}
									break;
								}
							case Identity.reset_USERPASSWORD:
								{
									if (msg.Status)
									{
										MessageBox.Show("User Password Reset Successfully");
									}
									else
									{
										MessageBox.Show("User password reset failed");
									}
									break;
								}
							case Identity.update_USERPASSWORD:
								{
									if (msg.Status)
									{
										MessageBox.Show("User Password modification Successfully");
									}
									else
									{
										MessageBox.Show("User password modification failed ");
									}
									break;
								}
							case Identity.update_SHIFT:
								{
									if (msg.Status)
									{
										DataTable shifttable = JsonHelper.DeserializeJsonToObject<DataTable>(msg.Parameter[0]);
										shifttable.TableName = SHIFT_TABLE.tableName;
										RefreshUserManagerList(shifttable);
									}
									else
									{
										MessageBox.Show("Shift modification failed");
									}
									break;
								}
							case Identity.update_TEAM:
								{
									if (msg.Status)
									{
										DataTable teamtable = JsonHelper.DeserializeJsonToObject<DataTable>(msg.Parameter[0]);
										teamtable.TableName = TEAM_TABLE.tableName;
										RefreshUserManagerList(teamtable);
									}
									else
									{
										MessageBox.Show("Team modification failed");
									}
									break;
								}
							case Identity.refrushShiftTable:
								{
									if (msg.Status)
									{
										DataTable shifttable = JsonHelper.DeserializeJsonToObject<DataTable>(msg.Parameter[0]);
										shifttable.TableName = SHIFT_TABLE.tableName;
										RefreshUserManagerList(shifttable);
									}
									else
									{
										MessageBox.Show("Shift refresh failed");
									}
									break;
								}
							default:
								{
									break;
								}
						}
					}
					else
					{
						MessageBox.Show("Command is not valid");
					}
				}
			}
			catch (Exception ex)
			{
				LogHelper.WriteLog("Client_DealMessageHandler", ex);
				MessageBox.Show(ex.Message);
			}
		}
		#endregion

		#region User/Shift display
		public void RefreshUserManagerList(DataTable dataTable)
		{
			if (dataTable.TableName == USER_TABLE.tableName)
			{
				if (dataTable.Rows.Count > 0)
				{
					DataTable userTable = dataTable.DefaultView.ToTable(USER_TABLE.tableName, true, new string[] { USER_TABLE.fd_userNo, USER_TABLE.fd_userName, USER_TABLE.fd_userLevel, USER_TABLE.fd_createDate, USER_TABLE.fd_userDepartment, USER_TABLE.fd_shiftName });
					userTable.Columns[USER_TABLE.fd_userNo].ColumnName = "UserID";
					userTable.Columns[USER_TABLE.fd_userLevel].ColumnName = "AccountType";
					userTable.Columns[USER_TABLE.fd_userDepartment].ColumnName = "Department";
					Dispatcher.Invoke(new Action(() =>
					{
						dataGrid_UserDetail.ItemsSource = userTable.DefaultView;
					}
					));
				}
			}
			else if (dataTable.TableName == SHIFT_TABLE.tableName)
			{
				Dispatcher.Invoke(new Action(() =>
				{
					if (dataTable != null && dataTable.Rows.Count > 0)
					{
						//加载班组下拉框
						comboBox_UserShift.Items.Clear();
						for (int i = 0; i < dataTable.Rows.Count; i++)
						{
							comboBox_UserShift.Items.Add(dataTable.Rows[i][USER_TABLE.fd_shiftName].ToString());
						}
						//DataRow[] unrows = dataTable.Select("shift_name is not null");
						//pre_shift_table = unrows.CopyToDataTable();
					}
					dataGrid_ShiftDetail.ItemsSource = dataTable.DefaultView;
				}
				));
			}
			else if (dataTable.TableName == TEAM_TABLE.tableName)
			{
				Dispatcher.Invoke(new Action(() =>
				{
					dataGrid_TeamDetail.ItemsSource = dataTable.DefaultView;
				}
					));
			}
		}
		#endregion
		
		#region Popup_Edit_Password Dragable
		bool isDownPopup_Edit_Password;
		Point originalPointPopup_Edit_Password;

		public Point OriginalPointPopup_Edit_Password { get => originalPointPopup_Edit_Password; set => originalPointPopup_Edit_Password = value; }
		public bool IsDownPopup_Edit_Password { get => isDownPopup_Edit_Password; set => isDownPopup_Edit_Password = value; }
		private void btn_Popup_Edit_Password_ChangePosition_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
		{
			IsDownPopup_Edit_Password = true;
			OriginalPointPopup_Edit_Password = e.GetPosition(popup_Edit_Password);
		}

		private void btn_Popup_Edit_Password_ChangePosition_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
		{
			IsDownPopup_Edit_Password = false;
		}

		private void btn_Popup_Edit_Password_ChangePosition_PreviewMouseMove(object sender, MouseEventArgs e)
		{
			if (IsDownPopup_Edit_Password)
			{
				Point pos = e.GetPosition(popup_Edit_Password);
				popup_Edit_Password.HorizontalOffset += pos.X - OriginalPointPopup_Edit_Password.X;
				popup_Edit_Password.VerticalOffset += pos.Y - OriginalPointPopup_Edit_Password.Y;
				OriginalPointPopup_Edit_Password = pos;
			}
		}
		#endregion
		#region Popup_Shift Dragable
		bool isDownPopup_Shift;
		Point originalPointPopup_Shift;

		public Point OriginalPointPopup_Shift { get => originalPointPopup_Shift; set => originalPointPopup_Shift = value; }
		public bool IsDownPopup_Shift { get => isDownPopup_Shift; set => isDownPopup_Shift = value; }
		private void btn_Popup_Shift_ChangePosition_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
		{
			IsDownPopup_Shift = true;
			OriginalPointPopup_Shift = e.GetPosition(Popup_Shift);
		}

		private void btn_Popup_Shift_ChangePosition_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
		{
			IsDownPopup_Shift = false;
		}

		private void btn_Popup_Shift_ChangePosition_PreviewMouseMove(object sender, MouseEventArgs e)
		{
			if (IsDownPopup_Shift)
			{
				Point pos = e.GetPosition(Popup_Shift);
				Popup_Shift.HorizontalOffset += pos.X - OriginalPointPopup_Shift.X;
				Popup_Shift.VerticalOffset += pos.Y - OriginalPointPopup_Shift.Y;
				OriginalPointPopup_Shift = pos;
			}
		}
		#endregion
		#region Popup_Team Dragable
		bool isDownPopup_Team;
		Point originalPointPopup_Team;

		public Point OriginalPointPopup_Team { get => originalPointPopup_Team; set => originalPointPopup_Team = value; }
		public bool IsDownPopup_Team { get => isDownPopup_Team; set => isDownPopup_Team = value; }
		private void btn_Popup_Team_ChangePosition_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
		{
			IsDownPopup_Team = true;
			OriginalPointPopup_Team = e.GetPosition(Popup_Team);
		}

		private void btn_Popup_Team_ChangePosition_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
		{
			IsDownPopup_Team = false;
		}

		private void btn_Popup_Team_ChangePosition_PreviewMouseMove(object sender, MouseEventArgs e)
		{
			if (IsDownPopup_Team)
			{
				Point pos = e.GetPosition(Popup_Team);
				Popup_Team.HorizontalOffset += pos.X - OriginalPointPopup_Team.X;
				Popup_Team.VerticalOffset += pos.Y - OriginalPointPopup_Team.Y;
				OriginalPointPopup_Team = pos;
			}
		}
		#endregion

		#region User Operate
		/// <summary>
		/// new user 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btn_new_User_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				Grid_UserDetail.IsEnabled = true;
				btn_SaveUser_Content = "New";
				textBox_UserID.IsEnabled = true;
				textBox_UserName.IsEnabled = true;
				textBox_UserPassword.IsEnabled = true;
				textBox_UserConfirmPassword.IsEnabled = true;
				comboBox_UserDepartment.IsEnabled = true;
				comboBox_UserLevel.IsEnabled = true;
				comboBox_UserShift.IsEnabled = true;

				textBox_UserID.Text = "";
				textBox_UserName.Text = "";
				comboBox_UserDepartment.Text = "";
				comboBox_UserLevel.Text = "";
				comboBox_UserShift.Text = "";
			}
			catch (Exception ex)
			{
				LogHelper.WriteLog("btn_new_User_Click", ex);
			}			
		}
		/// <summary>
		/// save user
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btn_save_User_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				if (btn_SaveUser_Content == "New")
				{
					if (textBox_UserID.Text == "" || textBox_UserName.Text == "" || textBox_UserPassword.Password.Trim() == "" || textBox_UserConfirmPassword.Password.Trim() == "")
					{
						MessageBox.Show("User Name,User Number,User Password cannot be empty");
						return;
					}
					if (comboBox_UserDepartment.Text == "" || comboBox_UserLevel.Text == "" || comboBox_UserShift.Text.Trim() == "")
					{
						MessageBox.Show("User Department,User Level,User Shift cannot be empty");
						return;
					}
					if (textBox_UserPassword.Password.Trim() != textBox_UserConfirmPassword.Password.Trim())
					{
						MessageBox.Show("Inconsistent passwords");
						return;
					}
					int userid = 0;
					if (!int.TryParse(textBox_UserID.Text, out userid))
					{
						MessageBox.Show("User id must be digital ");
						return;
					}
					if (MessageBox.Show("Are you sure you want to save the User?", "SAVE", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.OK)
					{
						client.SendMessage(Identity.definedCommand, Identity.insert_USER, textBox_UserID.Text.ToString() + ";" + textBox_UserName.Text.ToString() + ";" + comboBox_UserLevel.Text.ToString() + ";" + DateTime.Now.ToString(Formats.GetDateFormat()) + ";" + comboBox_UserDepartment.Text.ToString() + ";"
					   + comboBox_UserShift.Text.ToString() + ";" + textBox_UserPassword.Password.ToString());
					}
				}
				else if (btn_SaveUser_Content == "Edit")
				{
					var drvuser = dataGrid_UserDetail.SelectedItem as DataRowView;
					if (drvuser != null)
					{
						if (comboBox_UserLevel.Text.ToString() == "")
						{
							MessageBox.Show("User level cannot be empty");
							return;
						}
						if (MessageBox.Show("Are you sure you want to save the User?", "SAVE", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.OK)
						{
							client.SendMessage(Identity.definedCommand, Identity.update_USER, textBox_UserID.Text.ToString() + ";" + textBox_UserName.Text.ToString() + ";" + comboBox_UserLevel.Text.ToString() +
							";" + comboBox_UserDepartment.Text.ToString() + ";" + comboBox_UserShift.Text.ToString());
						}
					}
				}
			}
			catch (Exception ex)
			{
				LogHelper.WriteLog("btn_new_User_Click", ex);
			}			
		}
		/// <summary>
		/// edit user
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btn_edit_User_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				if (dataGrid_UserDetail.SelectedItem == null)
				{
					MessageBox.Show("please select a user");
					return;
				}
				Grid_UserDetail.IsEnabled = true;
				btn_SaveUser_Content = "Edit";
				textBox_UserID.IsEnabled = false;
				textBox_UserPassword.IsEnabled = false;
				textBox_UserConfirmPassword.IsEnabled = false;
				textBox_UserName.IsEnabled = true;
				comboBox_UserDepartment.IsEnabled = true;
				comboBox_UserLevel.IsEnabled = true;
				comboBox_UserShift.IsEnabled = true;
			}
			catch (Exception ex)
			{
				LogHelper.WriteLog("btn_new_User_Click", ex);
			}			
		}
		/// <summary>
		/// delete user
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btn_delete_User_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				if (dataGrid_UserDetail.SelectedItem == null)
				{
					MessageBox.Show("please select a user");
					return;
				}
				if (MessageBox.Show("Are you sure you want to delete the User?", "DELETE", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.OK)
				{
					var drvuser = dataGrid_UserDetail.SelectedItem as DataRowView;
					if (drvuser != null)
					{
						client.SendMessage(Identity.definedCommand, Identity.delete_USER, drvuser.Row["UserID"].ToString());
					}
				}
			}
			catch (Exception ex)
			{
				LogHelper.WriteLog("btn_delete_User_Click", ex);
				throw ex;
			}
			
		}
		/// <summary>
		/// user table data selectionchanged
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void dataGrid_UserDetail_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			try
			{
				var drvuser = dataGrid_UserDetail.SelectedItem as DataRowView;
				if (drvuser != null)
				{
					string user_id = drvuser.Row["UserID"].ToString();
					string user_name = drvuser.Row[USER_TABLE.fd_userName].ToString();
					string user_level = drvuser.Row["AccountType"].ToString();
					string user_department = drvuser.Row["Department"].ToString();
					string user_shift = drvuser.Row[USER_TABLE.fd_shiftName].ToString();
					textBox_UserID.Text = user_id;
					textBox_UserName.Text = user_name;
					comboBox_UserDepartment.Text = user_department;
					comboBox_UserLevel.Text = user_level;
					comboBox_UserShift.Text = user_shift;
				}
				Grid_UserDetail.IsEnabled = false;
			}
			catch (Exception ex)
			{
				LogHelper.WriteLog("btn_new_User_Click", ex);
			}			
		}
		/// <summary>
		/// modify user password
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btn_edit_Password_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				popup_Edit_Password.IsOpen = true;
				textBox_Edit_UserName.Text = USER_TABLE.user_Name;
				textBox_Edit_UserID.Text = USER_TABLE.user_No;
			}
			catch (Exception ex)
			{
				LogHelper.WriteLog("btn_new_User_Click", ex);
			}			
		}
		/// <summary>
		/// reset user password
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btn_reset_Password_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				if (dataGrid_UserDetail.SelectedItem == null)
				{
					MessageBox.Show("please select a user");
					return;
				}
				if (MessageBox.Show("Are you sure you want to reset the User Password?", "RESET", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.OK)
				{
					var drvuser = dataGrid_UserDetail.SelectedItem as DataRowView;
					if (drvuser != null)
					{
						client.SendMessage(Identity.definedCommand, Identity.reset_USERPASSWORD, drvuser.Row["UserID"].ToString());
					}
				}
			}
			catch (Exception ex)
			{
				LogHelper.WriteLog("btn_new_User_Click", ex);
			}			
		}
		/// <summary>
		/// close popup edit password
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btn_popup_close_Click(object sender, RoutedEventArgs e)
		{
			popup_Edit_Password.IsOpen = false;
		}
		/// <summary>
		/// save user password
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btn_Save_Password_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				if (textBox_Edit_OldPassword.Password != USER_TABLE.user_Password)
				{
					MessageBox.Show("User password error");
					return;
				}
				if (textBox_Edit_NewPassword.Password != textBox_Edit_ConfirmPassword.Password)
				{
					MessageBox.Show("Inconsistent passwords.");
					return;
				}
				client.SendMessage(Identity.definedCommand, Identity.update_USERPASSWORD, textBox_Edit_UserID.Text.ToString() + ";" + textBox_Edit_NewPassword.Password.ToString());
			}
			catch (Exception ex)
			{
				LogHelper.WriteLog("btn_new_User_Click", ex);
			}
			
		}
		private DataTable CreateUserTable(string user_No, string user_Name, string user_Password, string user_Level, string create_Date, string user_Dep, string shift_Name, string update_Time)
		{
			DataTable dt = new DataTable(USER_TABLE.tableName);
			DataColumn dc1 = new DataColumn(USER_TABLE.fd_userNo, Type.GetType("System.String"));
			DataColumn dc2 = new DataColumn(USER_TABLE.fd_userName, Type.GetType("System.String"));
			DataColumn dc3 = new DataColumn(USER_TABLE.fd_userPassword, Type.GetType("System.String"));
			DataColumn dc4 = new DataColumn(USER_TABLE.fd_userLevel, Type.GetType("System.String"));
			DataColumn dc5 = new DataColumn(USER_TABLE.fd_createDate, Type.GetType("System.String"));
			DataColumn dc6 = new DataColumn(USER_TABLE.fd_userDepartment, Type.GetType("System.String"));
			DataColumn dc7 = new DataColumn(USER_TABLE.fd_shiftName, Type.GetType("System.String"));
			DataColumn dc8 = new DataColumn(USER_TABLE.fd_updateTime, Type.GetType("System.String"));
			dt.Columns.Add(dc1);
			dt.Columns.Add(dc2);
			dt.Columns.Add(dc3);
			dt.Columns.Add(dc4);
			dt.Columns.Add(dc5);
			dt.Columns.Add(dc6);
			dt.Columns.Add(dc7);
			dt.Columns.Add(dc8);

			DataRow dr = dt.NewRow();
			dr[USER_TABLE.fd_userNo] = user_No;
			dr[USER_TABLE.fd_userName] = user_Name;
			dr[USER_TABLE.fd_userPassword] = user_Password;
			dr[USER_TABLE.fd_userLevel] = user_Level;
			dr[USER_TABLE.fd_createDate] = DateTime.Now.ToString(Formats.GetDateFormat());
			dr[USER_TABLE.fd_userDepartment] = user_Dep;
			dr[USER_TABLE.fd_shiftName] = shift_Name;
			dr[USER_TABLE.fd_updateTime] = update_Time;
			dt.Rows.Add(dr);
			return dt;
		}
		#endregion

		#region Shift Operate
		/// <summary>
		/// TextChanged
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void dateTimePickerDaystarttime_TextChanged(object sender, EventArgs e)
		{
			try
			{
				int dayEndTimeint = Convert.ToInt32(dateTimePickerDaystarttime.Value.ToString(Formats.GetTimeHourFormat())) + 12;
				if (dayEndTimeint > 24)
				{
					dayEndTimeint = dayEndTimeint - 24;
				}
				string dayEndTime = dayEndTimeint.ToString() + ":00:00";
				dateTimePickerDaystarttime.Value = Convert.ToDateTime(dateTimePickerDaystarttime.Value.ToString(Formats.GetTimeHourFormat()) + ":00:00");
				dateTimePickerDayendtime.Value = Convert.ToDateTime(dayEndTime);
				dateTimePickerNightstarttime.Value = dateTimePickerDayendtime.Value;
				dateTimePickerNightendtime.Value = dateTimePickerDaystarttime.Value;
			}
			catch (Exception ex)
			{
				LogHelper.WriteLog("btn_new_User_Click", ex);
			}
			
		}
		/// <summary>
		/// edit shift
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btn_editShift_Click(object sender, RoutedEventArgs e)
		{
			Popup_Shift.IsOpen = true;
		}
		/// <summary>
		/// save shift information
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btn_SaveShift_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				string dayStartTime = dateTimePickerDaystarttime.Value.ToString(Formats.GetTimeHourFormat());
				string dayEndTime = dateTimePickerDayendtime.Value.ToString(Formats.GetTimeHourFormat());
				if (dayStartTime == dayEndTime)
				{
					MessageBox.Show("Please modify the day shift start time");
					return;
				}
				DataTable shiftTable = new DataTable();
				shiftTable.Columns.Add(SHIFT_TABLE.fd_shiftName, typeof(string));
				shiftTable.Columns.Add(SHIFT_TABLE.fd_startTime, typeof(string));
				shiftTable.Columns.Add(SHIFT_TABLE.fd_endTime, typeof(string));
				shiftTable.Rows.Add("DAY", dateTimePickerDaystarttime.Value.ToString(Formats.GetTimeFormat()), dateTimePickerDayendtime.Value.ToString(Formats.GetTimeFormat()));
				shiftTable.Rows.Add("NIGHT", dateTimePickerNightstarttime.Value.ToString(Formats.GetTimeFormat()), dateTimePickerNightendtime.Value.ToString(Formats.GetTimeFormat()));
				string jsonshiftinfo= JsonHelper.SerializeObject(shiftTable);
				client.SendMessage(Identity.definedCommand, Identity.update_SHIFT, jsonshiftinfo);				
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}
		/// <summary>
		/// close popup shift
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btn_CloseShift_Click(object sender, RoutedEventArgs e)
		{
			Popup_Shift.IsOpen = false;
		}

		#endregion

		#region Team Operate
		/// <summary>
		///team table data SelectionChanged
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void comboBox_DayShift_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			try
			{
				string selectDayShift = ((System.Windows.Controls.ComboBoxItem)comboBox_DayShift.SelectedItem).Content.ToString();
				if (selectDayShift == "A")
				{
					textBox_NightShift.Text = "B";
					textBox_DayShiftTwo.Text = "B";
					textBox_NightShiftTwo.Text = "C";
					textBox_DayShiftThree.Text = "C";
					textBox_NightShiftThree.Text = "D";
					textBox_DayShiftFour.Text = "D";
					textBox_NightShiftFour.Text = "A";
				}
				else if (selectDayShift == "B")
				{
					textBox_NightShift.Text = "C";
					textBox_DayShiftTwo.Text = "C";
					textBox_NightShiftTwo.Text = "D";
					textBox_DayShiftThree.Text = "D";
					textBox_NightShiftThree.Text = "A";
					textBox_DayShiftFour.Text = "A";
					textBox_NightShiftFour.Text = "B";
				}
				else if (selectDayShift == "C")
				{
					textBox_NightShift.Text = "D";
					textBox_DayShiftTwo.Text = "D";
					textBox_NightShiftTwo.Text = "A";
					textBox_DayShiftThree.Text = "A";
					textBox_NightShiftThree.Text = "B";
					textBox_DayShiftFour.Text = "B";
					textBox_NightShiftFour.Text = "C";
				}
				else if (selectDayShift == "D")
				{
					textBox_NightShift.Text = "A";
					textBox_DayShiftTwo.Text = "A";
					textBox_NightShiftTwo.Text = "B";
					textBox_DayShiftThree.Text = "B";
					textBox_NightShiftThree.Text = "C";
					textBox_DayShiftFour.Text = "C";
					textBox_NightShiftFour.Text = "D";
				}
			}
			catch (Exception ex)
			{
				LogHelper.WriteLog("btn_new_User_Click", ex);
			}
			
		}
		/// <summary>
		/// edit Team
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btn_edit_Team_Click(object sender, RoutedEventArgs e)
		{
			Popup_Team.IsOpen = true;
			//datePicker_ShiftDate.BlackoutDates.Add(new CalendarDateRange(DateTime.Now.Date.AddDays(1),new DateTime()));
		}
		/// <summary>
		/// save Team
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btn_SaveTeam_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				string shiftdate = datePicker_ShiftDate.SelectedDate?.ToString(Formats.GetShortFormat());
				if (comboBox_DayShift.Text == ""|| comboBox_DayShift.Text == "select")
				{
					MessageBox.Show("please select a day shift");
					return;
				}
				if (shiftdate == null)
				{
					MessageBox.Show("please select shift date");
					return;
				}
				DataTable teamTable = new DataTable();
				teamTable.Columns.Add(TEAM_TABLE.fd_shiftDate, typeof(string));
				teamTable.Columns.Add(TEAM_TABLE.fd_dayShift, typeof(string));
				teamTable.Columns.Add(TEAM_TABLE.fd_nightShift, typeof(string));
				
				teamTable.Rows.Add(shiftdate, comboBox_DayShift.Text, textBox_NightShift.Text);
				teamTable.Rows.Add("", textBox_DayShiftTwo.Text, textBox_NightShiftTwo.Text);
				teamTable.Rows.Add("", textBox_DayShiftThree.Text, textBox_NightShiftThree.Text);
				teamTable.Rows.Add("", textBox_DayShiftFour.Text, textBox_NightShiftFour.Text);
				string jsonteamtinfo = JsonHelper.SerializeObject(teamTable);
				client.SendMessage(Identity.definedCommand, Identity.update_TEAM, jsonteamtinfo);				
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}
		/// <summary>
		/// close Popup Team
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btn_CloseTeam_Click(object sender, RoutedEventArgs e)
		{
			Popup_Team.IsOpen = false;
		}				
		#endregion

		#region Kill Process
		private void Window_Closed(object sender, EventArgs e)
		{
			try
			{
				Process[] p = Process.GetProcessesByName(System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName.Replace(".exe", ""));
				p[0].Kill();
			}
			catch { }
			finally
			{
				Application.Current.Shutdown();
			}
		}
		#endregion		
	}
}
